$(document).ready(function() {
    $("#saveQuestionBtn").click(function () {
        var formData = {
            questionId: $("#editQuestionId").val(),
            questionText: $("#editQuestionTitle").val(),
            correctOption: $("#editCorrectOption").val(),
            optionA: $("#editOptionA").val(),
            optionB: $("#editOptionB").val(),
            optionC: $("#editOptionC").val(),
            optionD: $("#editOptionD").val()
        };

        $.ajax({
            url: '/teacher/updateQuestion',
            type: 'PUT',
            data: JSON.stringify(formData), // 转换为 JSON 字符串
            contentType: 'application/json', // 确保编码正确
            success: function (response) {
                if (response.code === 200) {
                    alert("试题更新成功！");
                    $("#editQuestionModal").modal("hide");
                    // 自动触发搜索功能
                    $("#searchQuestion").trigger("input");
                } else {
                    alert(response.msg);
                }
            },
            error: function () {
                alert("更新请求失败！");
            }
        });
    });

    // 搜索功能
    $("#searchQuestion").on("input", function () {
        var keyword = $(this).val().trim();

        $.ajax({
            url: '/teacher/searchQuestions', // 搜索试题接口
            type: 'GET',
            data: { keyword: keyword },
            success: function (response) {
                if (response.code === 200) {
                    var tableBody = $("#questionTable tbody");
                    tableBody.empty();
                    response.data.forEach(function (question) {
                        var row = `<tr>
                                <td>${question.questionId}</td>
                                <td>${question.questionText}</td>
                                <td>${question.correctOption}</td>
                                <td>
                                    <button class="btn btn-warning btn-sm edit-btn" data-id="${question.questionId}">编辑</button>
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="${question.questionId}">删除</button>
                                </td>
                              </tr>`;
                        tableBody.append(row);
                    });
                } else {
                    alert('搜索失败: ' + response.message);
                }
            },
            error: function () {
                alert("搜索请求失败，请重试！");
            }
        });
    });


    // 添加新试题表单提交
    $("#addQuestionForm").submit(function (event) {
        event.preventDefault();

        // 获取表单数据
        var formData = {
            title: $("#questionTitle").val(),
            answer: $("#questionAnswer").val(),
            optionA: $("#optionA").val(),
            optionB: $("#optionB").val(),
            optionC: $("#optionC").val(),
            optionD: $("#optionD").val()
        };

        // 异步请求添加试题
        $.ajax({
            url: '/teacher/addQuestion',  // 后端接口地址
            type: 'POST',
            data: formData,
            success: function (response) {
                if (response.code===200) {
                    alert("试题添加成功!");
                    loadQuestions(); // 重新加载试题列表
                    $("#addQuestionForm")[0].reset();  // 清空表单
                } else {
                    alert("添加失败: " + response.message);
                }
            },
            error: function () {
                alert("请求失败，请重试！");
            }
        });
    });


    $(document).on("click", ".delete-btn", function () {
        var questionId = $(this).data("id");

        if (confirm("确定删除该试题吗？")) {
            $.ajax({
                url: '/teacher/deleteQuestion/' + questionId,
                type: 'DELETE',
                success: function (response) {
                    if (response.code === 200) {
                        alert("试题删除成功！");
                        // 自动触发搜索功能
                        loadQuestions()
                        // $("#searchQuestion").trigger("input");
                    } else {
                        alert("删除失败: " + response.msg);
                    }
                },
                error: function () {
                    alert("删除请求失败！");
                }
            });
        }
    });

    function loadQuestions() {
        $.ajax({
            url: '/teacher/getAllQuestions',  // 获取所有试题接口
            type: 'GET',
            success: function(response) {
                if(response.code===200){
                    var tableBody = $("#questionTable tbody");
                    tableBody.empty();  // 清空表格内容
                    // 填充表格数据
                    response.data.forEach(function(question) {
                        console.log(question)
                        const a=1
                        var row = `'<tr>
                                    <td>${question.questionId}</td>
                                    <td>${question.questionText}</td>
                                    <td>${question.correctOption}</td>
                                    <td>
                                        <button class="btn btn-warning btn-sm edit-btn" data-id="${question.questionId}">编辑</button>
                                        <button class="btn btn-danger btn-sm delete-btn" data-id="${question.questionId}">删除</button>
                                    </td>
                                  </tr>'`;
                        tableBody.append(row);
                    });
                    return;
                }
                alert('获取数据失败')
            },
            error: function() {
                alert("加载试题列表失败！");
            }
        });


        $(document).on("click", ".edit-btn", function () {
            var questionId = $(this).data("id");

            // 获取题目详情
            $.ajax({
                url: '/teacher/getQuestionDetails',
                type: 'GET',
                data: { id: questionId },
                success: function (response) {
                    console.log(response.data)
                    if (response.code === 200) {
                        console.log('问题详情',response.data)
                        // 填充模态框内容
                        $("#editQuestionId").val(response.data.questionId);
                        $("#editQuestionTitle").val(response.data.questionText);
                        $("#editOptionA").val(response.data.optionA);
                        $("#editOptionB").val(response.data.optionB);
                        $("#editOptionC").val(response.data.optionC);
                        $("#editOptionD").val(response.data.optionD);
                        $("#editCorrectOption").val(response.data.correctOption);

                        // 显示模态框
                        $("#editQuestionModal").modal("show");
                    } else {
                        alert("获取题目详情失败: " + response.msg);
                    }
                },
                error: function () {
                    alert("请求失败，请重试！");
                }
            });
        });

    }
    // 页面加载时自动加载试题列表
    loadQuestions();
});
